namespace EmailParser
{
    using System;
    using System.Collections.Generic;
    using System.Text;
    using ImapX;

    public class EmailParser
    {
        public List<ParseError> _badParseItems = new List<ParseError>();
        private int _bodyEndIndex;
        private int _bodyStartIndex;
        public List<string> _boundaryCollection = new List<string>();
        public string[] _emailItems;
        private int _headerEndIndex;
        private string _headerLastKey;
        public Dictionary<string, string> _headersCollection = new Dictionary<string, string>();
        private int _headerStartIndex;
        public List<BodyPart> _parts = new List<BodyPart>();
        public const string BOUNDARY = "boundary=";
        public const string BOUNDARY_END_SYMBOLS = "--";
        public const string CRLN = "\r\n";
        private bool isEmailValid = true;
        public const char SPACE = ' ';
        public const char TAB = '\t';

        public EmailParser(string[] email)
        {
            this._emailItems = email;
        }

        public string GetPart(BodyPart p)
        {
            StringBuilder builder = new StringBuilder();
            bool flag = true;
            foreach (int num in p.BodyIndexes)
            {
                if (flag)
                {
                    builder.Append(this._emailItems[num]);
                    flag = false;
                }
                else
                {
                    builder.Append("\r\n" + this._emailItems[num]);
                }
            }
            if ((p.Boundary == null) && (builder.Length > 0))
            {
                char ch = builder[builder.Length - 1];
                if (ch.Equals(')'))
                {
                    builder = builder.Remove(builder.Length - 1, 1);
                }
            }
            return builder.ToString();
        }

        public void InitializeIndexes()
        {
            for (int i = 0; i < this._emailItems.Length; i++)
            {
                if (string.IsNullOrEmpty(this._emailItems[i]))
                {
                    this._headerStartIndex = 0;
                    this._headerEndIndex = i;
                    this._bodyStartIndex = i + 1;
                    this._bodyEndIndex = this._emailItems.Length - 2;
                    return;
                }
            }
            throw new ImapException("No headers found.");
        }

        public void ParseBody()
        {
            BodyPart item = new BodyPart();
            item.Boundary = null;
            if (this._boundaryCollection.Count < 1)
            {
                for (int i = this._bodyStartIndex; i <= this._bodyEndIndex; i++)
                {
                    item.BodyIndexes.Add(i);
                }
            }
            else
            {
                for (int j = this._bodyStartIndex; j < this._bodyEndIndex; j++)
                {
                    if ((this._boundaryCollection.Count > 0) && this._emailItems[j].Contains(this._boundaryCollection[0] + "--"))
                    {
                        break;
                    }
                    foreach (string str in this._boundaryCollection)
                    {
                        if (this._emailItems[j].Contains(str))
                        {
                            if (item.Boundary != null)
                            {
                                this._parts.Add(item);
                            }
                            item = new BodyPart();
                            item.Boundary = str;
                            j++;
                            while ((this._bodyEndIndex >= j) && (this._emailItems[j] != string.Empty))
                            {
                                if (this._emailItems[j].Contains("boundary="))
                                {
                                    try
                                    {
                                        string str2 = this._emailItems[j].Split(new string[] { "boundary=" }, StringSplitOptions.None)[1];
                                        if (str2.Contains(";"))
                                        {
                                            str2 = str2.Substring(0, str2.IndexOf(';'));
                                        }
                                        if (str2.Contains("\""))
                                        {
                                            str2 = str2.Replace("\"", "");
                                        }
                                        this._boundaryCollection.Add(str2);
                                    }
                                    catch (Exception exception)
                                    {
                                        this._badParseItems.Add(new ParseError(this._emailItems[j], exception));
                                    }
                                }
                                int index = this._emailItems[j].IndexOf(':');
                                try
                                {
                                    char ch = '\t';
                                    char ch2 = ' ';
                                    if (((index > 0) & !this._emailItems[j].StartsWith(ch.ToString())) & !this._emailItems[j].StartsWith(ch2.ToString()))
                                    {
                                        string str3 = this._emailItems[j].Substring(0, index);
                                        string str4 = this._emailItems[j].Substring(index + 2);
                                        this._headerLastKey = str3;
                                        item.Headers.Add(str3.Trim(new char[] { ' ' }), str4.Trim(new char[] { ' ' }));
                                    }
                                    else
                                    {
                                        Dictionary<string, string> dictionary;
                                        string str5;
                                        (dictionary = item.Headers)[str5 = this._headerLastKey] = dictionary[str5] + "\n" + this._emailItems[j];
                                    }
                                }
                                catch (Exception exception2)
                                {
                                    this._badParseItems.Add(new ParseError(this._emailItems[j], exception2));
                                }
                                j++;
                            }
                            j++;
                            break;
                        }
                    }
                    item.BodyIndexes.Add(j);
                }
            }
            this._parts.Add(item);
        }

        public void ParseHeaders()
        {
            for (int i = this._headerStartIndex; i < this._headerEndIndex; i++)
            {
                if (this._emailItems[i].Contains("boundary="))
                {
                    try
                    {
                        string item = this._emailItems[i].Split(new string[] { "boundary=" }, StringSplitOptions.None)[1];
                        if (item.Contains(";"))
                        {
                            item = item.Substring(0, item.IndexOf(';'));
                        }
                        if (item.Contains("\""))
                        {
                            item = item.Replace("\"", "");
                        }
                        this._boundaryCollection.Add(item);
                    }
                    catch (Exception exception)
                    {
                        this._badParseItems.Add(new ParseError(this._emailItems[i], exception));
                    }
                }
                int index = this._emailItems[i].IndexOf(':');
                try
                {
                    char ch = '\t';
                    char ch2 = ' ';
                    if (((index > 0) & !this._emailItems[i].StartsWith(ch.ToString())) & !this._emailItems[i].StartsWith(ch2.ToString()))
                    {
                        string str2 = this._emailItems[i].Substring(0, index).Trim();
                        string str3 = "";
                        if (index + 2 < _emailItems[i].Length)
                        {
                            str3 = this._emailItems[i].Substring(index + 2).Trim();
                        }
                        this._headerLastKey = str2;
                        if (_headersCollection.ContainsKey(str2))
                        {
                            this._badParseItems.Add(new ParseError(this._emailItems[i], new Exception("Tried to add '" + str2 + "' as key to header collection but key already exists")));
                        }
                        else
                        {
                            this._headersCollection.Add(str2, str3);
                        }
                    }
                    else if (_headerLastKey != null)
                    {
                        Dictionary<string, string> dictionary;
                        string str4 = this._headerLastKey;
                        (dictionary = this._headersCollection)[str4] = dictionary[str4] + "\n" + this._emailItems[i];
                    }
                    else
                    {
                        this._badParseItems.Add(new ParseError(this._emailItems[i], new Exception("Tried to add to collection when _headerLastKey was null")));
                    }
                }
                catch (Exception exception2)
                {
                    this._badParseItems.Add(new ParseError(this._emailItems[i], exception2));
                }
            }
        }
    }
}

